package com.sdry.web.controller.plan;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.model.lz.Materiel;
import com.sdry.model.plan.StorageArea;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.plan.StorageAreaService;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;
/**
 *
 *@ClassName: StorageAreaController
 *@Description: 线边库表
 *@Author llm
 *@Date 2019-07-02 18:07:57
 *@version 1.0
*/
@Controller
@RequestMapping("/storageAreaManager")
public class StorageAreaController{
	@Resource StorageAreaService storageAreaService;
	/** 
	 * 进入页面
	 * @param model
	 * @return 页面路径
	*/
	@RequestMapping("/page")
	public String pageStorageArea (Model model) {
		return "/plan/storageArea";
	}
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public StorageArea queryById(Long id) {
		StorageArea param = storageAreaService.queryById(id);
		return param;
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<StorageArea> queryAllByMution(StorageArea param) {
		List<StorageArea> list = storageAreaService.queryAllByMution(param);
		return list;
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/list")
	public void list(StorageArea param,HttpServletResponse response){
		/*
		 * 条件分页查询内容
		 */
		List<StorageArea> list = storageAreaService.findPageByMution(param);
		/*
		 * 条件查询总条数
		 */
		Integer total = storageAreaService.selectCountByMution(param);
		/*
		 * 转为json数据传至页面
		 */
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/insert")
	public void insert(StorageArea param, HttpServletResponse response){
		System.out.println(param.toString());
		System.out.println(param);
		Long id = storageAreaService.insert(param);
		try {
			response.getWriter().print(id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/update")
	public void update(StorageArea param,HttpServletResponse response){
		Integer count = storageAreaService.update(param);
		try {
			response.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletResponse response){
		ids=ids.replace("'",""); 
		Integer count = storageAreaService.delete(ids);
		try {
			response.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 导入线边库
	 * @param file	上传的文件
	 * @param response
	 */
	@RequestMapping(value="/upload", method = RequestMethod.POST)
    @ResponseBody
	public void upload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
	    String savePath = "";
		// 1.获取原文件名1
        String fileName = file.getOriginalFilename();
		// 2.获取要保存的路径文件夹1
		String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
		// 3.保存
		savePath = realPath + "\\" + fileName;
		File desFile = new File(savePath);
		try {
			//把文件内容存入
			file.transferTo(desFile);
			//取文件后缀
			String subfix = fileName.lastIndexOf(".")==-1? "" : fileName.substring(fileName.lastIndexOf(".")+1);
			List<List<String>> lists = new ArrayList<>();
			//获取导入列数
			int num = 20;
			//用工具类读取导入的文件
			if(subfix.equals("xls")){
				lists = ExcelUtils.readXls(savePath, request, num);
			}else if(subfix.equals("xlsx")){
				lists = ExcelUtils.readXlsx(savePath, request, num);
			}
			Materiel m = new Materiel();
			StorageArea sa = new StorageArea();
			Long affact = 0L;
			int flag = 1;
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	        ZcSysUserEntity user = (ZcSysUserEntity)request.getSession().getAttribute("user");
	        sa.setUserId(user.getId());
	        sa.setCreateDate(sdf.format(new Date()));
	        //获取每一行要导入的数据，存入线边库
	        List<String> list = new ArrayList<>();
	        for (int i = 0; i < lists.size(); i++) {
	            list= lists.get(i);
	            m.setMateriel_name(list.get(4));
	            m.setMateriel_num(list.get(3));
	            Long mid = storageAreaService.findMaterielByNameAndNum(m);
	            sa.setMaterielId(mid);
	            sa.setBatch(list.get(2));
	            sa.setStorageQuantity(Integer.parseInt(list.get(6)));
	            sa.setMaterielQuantity(Integer.parseInt(list.get(5)));
	            sa.setSumQuantity(Integer.parseInt(list.get(7)));
	            sa.setRemark(list.get(8));
	            affact = storageAreaService.insert(sa);
	            if(affact <= 0){
	            	flag = 0;
	            	break;
	            }
	        }
			ResponseUtil.write(response, flag);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//-----------------------------------------------------app接口----------------------------------------------------------------------
	
	/**
	 * 根据主机厂查询物料
	 * @param customer 主机厂
	 * @throws Exception 
	 */
	@RequestMapping("/selectMaByCustomer")
	public void selectMaByCustomer(String customer, HttpServletResponse response) throws Exception {
		
		List<StorageArea> list = storageAreaService.selectMaByCustomer(customer);
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count>0) {
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 线边库提交
	 * @param param 线边库实体
	 * @param response 响应
	 */
	@RequestMapping("/submitStorage")
	public void submitStorage(String json, HttpServletResponse response) {
		Long affact = 0L;
		Integer count = 0;
		Gson gson = new Gson();
		List<StorageArea> storageAreas = gson.fromJson(json, new TypeToken<List<StorageArea>>() {}.getType());
		for (StorageArea storageArea : storageAreas) {
			StorageArea param = new StorageArea();
			param.setMaterielId(storageArea.getMaterielId());
			//先根据物料id查询此物料是否已存在
			List<StorageArea> list = storageAreaService.queryAllByMution(param);
			if(list.size() > 0) {
				//存在，修改
				StorageArea storageArea2 = list.get(0);
				storageArea2.setMaterielQuantity(storageArea.getMaterielQuantity());
				storageArea2.setUppers(storageArea.getUppers());
				storageArea2.setLowers(storageArea.getLowers());
				count = storageAreaService.update(storageArea2);
			}else {
				//不存在，添加
				affact = storageAreaService.insert(storageArea);
			}
		}
		
		JSONObject jsonObject = new JSONObject();
		if (affact > 0 || count > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", "提交成功");
		}else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "提交失败");
			jsonObject.put("data", "0");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
